package com.whj.apipassenger.interceptor;

import com.alibaba.nacos.api.utils.StringUtils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.whj.internalcommon.constant.TokenTypeConstants;
import com.whj.internalcommon.dto.ResponseResult;
import com.whj.internalcommon.dto.TokenResult;
import com.whj.internalcommon.utils.JwtUtils;
import com.whj.internalcommon.utils.RedisTokenKeyUtils;
import net.sf.json.JSONObject;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Auther: wanghaijun
 * @Date: 2023/1/1 - 01 - 01 - 13:50 
 * @Description: com.whj.apipassenger.interceptor
 */

public class JwtInterceptor implements HandlerInterceptor {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean result = true;
        String resultString = "";

        //获取请求中的token
        String token = request.getHeader("Authorization");

        //异常处理 解析token
        TokenResult tokenResult = JwtUtils.checkToken(token);

        //比较收到的token和redis中的token
        if (tokenResult == null) {
            resultString = "access token invalid";
            result = false;
        } else {
            //拼接key
            String phone = tokenResult.getPhone();
            String identity = tokenResult.getIdentity();
            String tokenKey = RedisTokenKeyUtils.keyByTokenMsg(phone, identity, TokenTypeConstants.ACCESS_TOKEN_TYPE);
            //从redis取出token
            String tokenRedis = stringRedisTemplate.opsForValue().get(tokenKey);

            //比较传入的token和redis中的token
            if ((StringUtils.isBlank(tokenRedis)) || (!tokenRedis.trim().equals(token))) {
                resultString = "access token invalid";
                result = false;
            }
        }

        if (!result) {
            PrintWriter out = response.getWriter();
            out.print(JSONObject.fromObject(ResponseResult.fail(resultString)).toString());
        }

        return result;
    }
}
